package com.yeqifu.bus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeqifu.bus.entity.Goods;
import com.yeqifu.bus.entity.GoodsDate;
import com.yeqifu.sys.common.TreeNode;
import com.yeqifu.sys.common.ResultObj;
import com.yeqifu.bus.entity.Provider;
import com.yeqifu.bus.service.IGoodsDateService;
import com.yeqifu.bus.service.IGoodsService;
import com.yeqifu.bus.service.IProviderService;
import com.yeqifu.bus.vo.GoodsDateVo;
import com.yeqifu.bus.vo.GoodsVo;
import com.yeqifu.sys.common.*;
import com.yeqifu.sys.entity.Dept;
import com.yeqifu.sys.service.IDeptService;
import com.yeqifu.sys.vo.DeptVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @since 2020-12-06
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IGoodsDateService goodsDateService;

    @Autowired
    private IProviderService providerService;

    @Autowired
    private IDeptService deptService;

    /**
     * 查询商品日期信息
     * @param goodsdateVo
     * @return
     */
    @RequestMapping("loadAllGoodsDate")
    public DataGridView loadAllGoodsDate(GoodsDateVo goodsdateVo){
        IPage<GoodsDate> page = new Page<GoodsDate>(goodsdateVo.getPage(),goodsdateVo.getLimit());
        QueryWrapper<GoodsDate> queryWrapper = new QueryWrapper<GoodsDate>();
        //编号查询
        queryWrapper.eq(goodsdateVo.getGoodsid()!=null&&goodsdateVo.getGoodsid()!=0,"goodsid",goodsdateVo.getGoodsid());
        //名称模糊查询
        queryWrapper.like(StringUtils.isNotBlank(goodsdateVo.getName()),"name",goodsdateVo.getName());
        //对时间进行查询要求大于开始时间小于结束时间
        queryWrapper.ge(goodsdateVo.getStartime()!=null,"qualdate",goodsdateVo.getStartime());
        queryWrapper.le(goodsdateVo.getEndtime()!=null,"qualdate",goodsdateVo.getEndtime());
        queryWrapper.eq(goodsdateVo.getDepotid()!=null,"depotid",goodsdateVo.getDepotid()).or().eq(goodsdateVo.getAreaid()!=null,"areaid",goodsdateVo.getAreaid());
        queryWrapper.orderByAsc("id");
        goodsDateService.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 查询商品具体信息
     * @param goodsVo
     * @return
     */
    @RequestMapping("loadAllGoods")
    public DataGridView loadAllGoods(GoodsVo goodsVo){
        IPage<Goods> page = new Page<Goods>(goodsVo.getPage(),goodsVo.getLimit());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq(goodsVo.getProviderid()!=null&&goodsVo.getProviderid()!=0,"providerid",goodsVo.getProviderid());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getGoodsname()),"goodsname",goodsVo.getGoodsname());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getProductcode()),"productcode",goodsVo.getProductcode());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getPromitcode()),"promitcode",goodsVo.getPromitcode());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getType()),"type",goodsVo.getType());
        queryWrapper.like(StringUtils.isNotBlank(goodsVo.getSize()),"size",goodsVo.getSize());
        //queryWrapper.eq(goodsVo.getDepotid()!=null&&goodsVo.getDepotid()!=0,"depotid",goodsVo.getDepotid());
        queryWrapper.eq(goodsVo.getDepotid()!=null,"depotid",goodsVo.getDepotid()).or().eq(goodsVo.getAreaid()!=null,"areaid",goodsVo.getAreaid());
        queryWrapper.orderByAsc("id");
        goodsService.page(page,queryWrapper);
        List<Goods> records = page.getRecords();
        for (Goods goods : records) {
            Provider provider = providerService.getById(goods.getProviderid());
            if (null!=provider){
                goods.setProvidername(provider.getProvidername());
            }
        }
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 加载左边的仓库树
     * @param deptVo
     * @return
     */
    @RequestMapping("loadDeptManagerLeftTreeJson")
    public DataGridView loadManagerLeftTreeJson(DeptVo deptVo){
        //查询出所有的部门，存放进list中
//        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq('1');
        List<Dept> list = deptService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        //将部门放入treeNodes中，组装成json
        for (Dept dept : list) {
            Boolean open = dept.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(dept.getId(),dept.getPid(),dept.getName(),open));
        }
        return new DataGridView(treeNodes);
    }

    /**
     * 添加商品
     * @param goodsVo
     * @return
     */
    @RequestMapping("addGoods")
    public ResultObj addGoods(GoodsVo goodsVo){
        try {
            System.out.println(goodsVo.getGoodsimg());
            if (goodsVo.getGoodsimg()!=null&&goodsVo.getGoodsimg().endsWith("_temp")){
                String newName = AppFileUtils.renameFile(goodsVo.getGoodsimg());
                goodsVo.setGoodsimg(newName);
            }
            goodsService.save(goodsVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改商品
     * @param goodsVo
     * @return
     */
    @RequestMapping("updateGoods")
    public ResultObj updateGoods(GoodsVo goodsVo){
        try {
            //商品图片不是默认图片
            if (!(goodsVo.getGoodsimg()!=null&&goodsVo.getGoodsimg().equals(Constast.DEFAULT_IMG_GOODS))){

                if (goodsVo.getGoodsimg().endsWith("_temp")){
                    String newName = AppFileUtils.renameFile(goodsVo.getGoodsimg());
                    goodsVo.setGoodsimg(newName);
                    //删除原先的图片
                    String oldPath = goodsService.getById(goodsVo.getId()).getGoodsimg();
                    AppFileUtils.removeFileByPath(oldPath);
                }
            }
            goodsService.updateById(goodsVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除商品
     * @param id 商品id
     * @return
     */
    @RequestMapping("deleteGoods")
    public ResultObj deleteGoods(Integer id,String goodsimg){
        try {

            //删除商品的图片
            AppFileUtils.removeFileByPath(goodsimg);
//            goodsService.removeById(id);
            goodsService.deleteGoodsById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 修改商品日期信息,其中修改批次数量
     * @param goodsdateVo
     * @return
     */
    @RequestMapping("updateGoodsDate")
    public ResultObj updateGoodsDate(GoodsDateVo goodsdateVo){
        try {
            goodsDateService.updateById(goodsdateVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }


    /**
     * 加载所有可用的商品
     * @return
     */
    @RequestMapping("loadAllGoodsForSelect")
    public DataGridView loadAllGoodsForSelect(){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Goods> list = goodsService.list(queryWrapper);
        for (Goods goods : list) {
            Provider provider = providerService.getById(goods.getProviderid());
            if (null!=provider){
                goods.setProvidername(provider.getProvidername());
            }
        }
        return new DataGridView(list);
    }

    /**
     * 加载所有可用的商品名称，用于搜索
     * @return
     */
    @RequestMapping("loadAllGoodsNameSelect")
    public DataGridView loadAllGoodsNameSelect(){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
        List<Goods> list = goodsService.list(queryWrapper);
        return new DataGridView(list);
    }

    /**
     * 加载所有可用的商品名称，消除重复列
     * 加载条件：剩余数量大于0
     * */
    @RequestMapping("loadAllDistinctGoods")
    public DataGridView loadAllDistinctGoods() {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("available", Constast.AVAILABLE_TRUE)
                .gt("number",0);
                //.select("distinct goodsname");
        List<Goods> goodsList = goodsService.list(queryWrapper);
        return new DataGridView(goodsService.list(queryWrapper));
    }


    /**
     * 根据供应商ID查询商品信息
     * @param providerid    供应商ID
     * @return
     */
    @RequestMapping("loadGoodsByProviderId")
    public DataGridView loadGoodsByProviderId(Integer providerid){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        queryWrapper.eq(providerid!=null,"providerid",providerid);
        List<Goods> list = goodsService.list(queryWrapper);
        for (Goods goods : list) {
            Provider provider = providerService.getById(goods.getProviderid());
            if (null!=provider){
                goods.setProvidername(provider.getProvidername());
            }
        }
        return new DataGridView(list);
    }

    //加载库存预警商品信息
    @RequestMapping("loadAllWarningGoods")
    public DataGridView loadAllWarningGoods(){
        List<Goods> goods = goodsService.loadAllWarning();
        return new DataGridView((long) goods.size(),goods);
     }

    //加载保质期预警商品信息
    @RequestMapping("loadAllDateWarningGoods")
    public DataGridView loadAllDateWarningGoods(){
        List<GoodsDate> goods = goodsService.loadAllDateWarning();
        return new DataGridView((long) goods.size(),goods);
    }



}

